package cn.framework.ajax;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

public class AjaxUtil {
	public HttpServletResponse response;
	private static AjaxUtil ajaxUtil;
	
	private AjaxUtil(HttpServletResponse response){
		response.setCharacterEncoding("UTF-8");
		this.response=response;
	};
	
	public static AjaxUtil getInstance(HttpServletResponse response){
		if (ajaxUtil == null) {
			 ajaxUtil = new AjaxUtil(response);
	     }
		ajaxUtil.setResponse(response);
		 return ajaxUtil;
	}
	
	public void wirte(AjaxModel ajaxModel){
		try {
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println(ajaxModel.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
	
	public void wirte(Exception exception){
		try {
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println(toAjax(exception));
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
	
	public static AjaxModel toAjax(Exception exception){
		AjaxModel ajaxModel=new AjaxModel(false);
		ajaxModel.setData(exception);
		ajaxModel.setMsg(exception.getMessage());
		return ajaxModel;
	}
	
	public static AjaxModel toAjax(Exception exception,String msg){
		AjaxModel ajaxModel=new AjaxModel(false);
		ajaxModel.setData(exception);
		ajaxModel.setMsg(msg);
		return ajaxModel;
	}
	
	public HttpServletResponse getResponse() {
		return response;
	}
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
}
